import { loginApi, getInfoApi, loginOutApi } from '@/api/user'
import { useRouter, useRoute } from 'vue-router'
import { defineStore } from 'pinia'
export default defineStore('user', {
    state:()=>{
        return {
            token: '', // 登录token
            info: {},  // 用户信息
        }
    },
    getters:{},
    actions:{
        tokenChange(token) {
            this.token = token
        },
        infoChange(info) {
            this.info = info
        },
        // login by login.vue
        login(params) {
            return new Promise((resolve, reject) => {
                const _this = this
                loginApi(params)
                    .then(res => {
                        _this.tokenChange(res.data.token)
                        _this.getInfo({ token: res.data.token })
                            .then(infoRes => {
                            resolve(res.data.token)
                        })
                    })
            })
        },
        // get user info after user logined
        getInfo(params) {
            const _this = this
            return new Promise((resolve, reject) => {
                getInfoApi(params)
                    .then(res => {
                        _this.infoChange(res.data.info)
                        resolve(res.data.info)
                    })
            })
        },
        loginOut() {
           return loginOutApi().then(res => {
                console.warn("退出登录...")
                }).catch(error => {
                console.warn("退出登录出现异常了...")
                })
                // .finally(() => {
                //     console.warn("退出登录后清理本地缓存....")
                //     // localStorage.removeItem('tabs')
                //     // localStorage.removeItem('vuex')
                //     useRouter().push("/login").then()
                //     //location.reload()
                // })
        }
    }
})
